<template>
  <div class="user-box">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="29">
        <el-col :span="7">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUsersList"
            @change="getUsersList()"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUsersList()"
            ></el-button>
          </el-input>
        </el-col>

        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">
            添加用户</el-button
          >
        </el-col>
      </el-row>

      <el-table :data="userlist" border stripe>
        <el-table-column type="index"> </el-table-column>
        <el-table-column label="姓名" prop="username"> </el-table-column>
        <el-table-column label="邮箱" prop="email"> </el-table-column>
        <el-table-column label="电话" prop="mobile"> </el-table-column>
        <el-table-column label="角色" prop="role_name"> </el-table-column>

        <!-- 状态 -->
        <el-table-column label="状态" pro="mg_state">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column label="操作" min-width="100px">
          <!-- 修改 -->
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="修改" placement="top">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="showEditDialog(scope.row.id)"
              ></el-button>
            </el-tooltip>

            <!-- 删除 -->
            <el-tooltip effect="dark" content="删除" placement="top">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="removeUserById(scope.row.id)"
              ></el-button>
            </el-tooltip>

            <!-- 分配角色按钮 -->
            <el-tooltip effect="dark" content="分配角色" placement="top">
              <el-button
                type="warning"
                icon="el-icon-lock"
                size="mini"
                @click="setUserRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页功能 -->

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClose"
    >
      <!-- 内容主体 -->

      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <!-- 用户名 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password"></el-input>
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <!-- 手机 -->
        <el-form-item label="手机" prop="phone">
          <el-input v-model="addForm.phone"></el-input>
        </el-form-item>
      </el-form>

      <!-- 内容底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户对话框 -->

    <el-dialog
      title="用户信息修改"
      :visible.sync="editDialogVisible"
      width="30%"
      @close="editDialogClose"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editForm"
        label-width="70px"
        class="demo-ruleForm"
      >
        <!-- 用户名 -->
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>

        <!-- prop设置的值是在 editFormRules中使用，作为验证的关键字 -->
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog title="" :visible.sync="setUserRoleDialogVisible" width="50%">
      <!-- 内容主体 -->
      <div>
        <p>用户id:{{ curUserSetRole.id }}</p>
        <p>用户名:{{ curUserSetRole.username }}</p>
        <p>用户当前角色:{{ curUserSetRole.role_name }}</p>
        <p>
          设置用户角色:
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolelist"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>

      <!-- 内容底部区域 -->
      <div slot="footer">
        <el-button @click="setUserRoleDialogClose()">取 消</el-button>
        <el-button type="primary" @click="saveUserRoleInfo(curUserSetRole.id,selectedRoleId)"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 自定义验证规则

    var checkEmail = (rule, value, cb) => {
      const regEmail =
        /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/;
      if (regEmail.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法邮箱"));
    };

    var checkPhone = (rule, value, cb) => {
      const regPhone = /^[1][3,4,5,7,8][0-9]{9}$/;
      // 合法调用回调函数
      if (regPhone.test(value)) {
        return cb();
      }
      // 不合法展示错误信息
      cb(new Error("请输入合法手机"));
    };

    return {
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
    //   用户列表
      userlist: [],
    //   角色列表
      rolelist:[],
  
      total: 0,
      // 控制添加用户对话框的显示与隐藏
      addDialogVisible: false,
      // 控制修改用户对话框的显示与隐藏
      editDialogVisible: false,
// 控制分配权限对话框的显示与隐藏
      setUserRoleDialogVisible: false,
        //   被选中的角色id
    selectedRoleId:'',
    //   当前需要分配角色的用户
       curUserSetRole:{},
      // 添加用户表单数据
      addForm: {
        username: "",
        password: "",
        email: "",
        phone: "",
      },
      // 修改用户表单
      editForm: {},
      // 添加用户表单规则
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkPhone, trigger: "blur" },
        ],
      },

      // 修改用户信息表单规则
      editFormRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkPhone, trigger: "blur" },
        ],
      },
    };
  },

  created() {
    this.getUsersList();
  },
  methods: {
    async getUsersList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200) return this.$message.error("获取用户失败");
      this.userlist = res.data.users;
      this.total = res.data.total;
    },
    handleSizeChange(val) {
      this.queryInfo.pagesize = val;
      this.getUsersList();
    },
    handleCurrentChange(val) {
      console.log(val);
    },
    
    //用户状态改变
    async userStateChange(userinfo) {
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      );
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state;
        return this.$message.error("更新用户状态失败");
      }
      this.$message.success("更新用户状态成功");
    },


    addDialogClose() {
      this.$refs.ruleForm.resetFields();
    },
    //添加用户操作
    addUser() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) return;
        // 可以发起真正的验证请求
        const { data: res } = await this.$http.post("users", {
          username: this.addForm.username,
          password: this.addForm.password,
          email: this.addForm.email,
          mobile: this.addForm.phone,
        });

        if (res.meta.status != 201) this.$message.error(res.meta.msg);
        this.$message.success(res.meta.msg);
        this.addDialogVisible = false;
        this.getUsersList();
      });
    },

    //修改用户信息
    async showEditDialog(id) {
      console.log(id);
      const { data: res } = await this.$http.get("users/" + id);
      if (res.meta.status !== 200)
        return this.$message.error("请求用户信息失败");
      this.editForm = res.data;
      this.editDialogVisible = true;
    },

    editDialogClose() {
      this.$refs.editForm.resetFields();
    },
    editUserInfo() {
      this.$refs.editForm.validate(async (valid) => {
        if (!valid) return;
        const { data: res } =await this.$http.put("users/"+this.editForm.id, {
      
          email:this.editForm.email,
          mobile: this.editForm.mobile,
        });
        console.log( this.editForm.id)
        if (res.meta.status !== 200) this.$message.error(res.meta.msg);
        this.$message.success(res.meta.msg);
        this.editDialogVisible = false;
        this.getUsersList();
      });
    },


    // 删除用户信息
    async removeUserById(id){
     const resConfirm =await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>{
          return err
        })

        // 如果用户确认 返回值为字符串confirm,
// 如果用户取消 ，返回值cancel
      if(resConfirm!=='confirm'){
       return this.$message.info('已经取消删除')
      }

      const {data:res} = await this.$http.delete('users/'+id)
      if(res.meta.status!==200){
        return this.$message.error(res.meta.msg)
      }

       this.$message.success(res.meta.msg)
      this.getUsersList();


    },


    // 设置用户角色
   async setUserRole(user){
       this.curUserSetRole = user
        this.setUserRoleDialogVisible =true
        // 获取角色列表
        const {data:res} = await this.$http.get('roles')
        if(res.meta.status!=200)return this.$message.error('获取角色列表失败')
        this.$message.success('获取角色列表成功')
        this.rolelist = res.data        
    },
    // 分配用户角色 点击对话框的 确定事件
   async saveUserRoleInfo(userid,roleid){
        const {data:res}= await  this.$http.put('users/'+userid+'/role',{rid:roleid})
        if(res.meta.status!=200)return this.$message.error('为用户分配角色失败')
        this.$message.success('为用户分配角色成功')
        this.setUserRoleDialogVisible =false
        this.getUsersList()
    },

    // 取消按钮的触发的事件
    setUserRoleDialogClose(){
        this.curUserSetRole=''
        this.selectedRoleId=''
        this.setUserRoleDialogVisible =false
    }



  },
};
</script>

<style scoped>
/* .user-box {
  line-height: 0;
} */
.cell{
   min-width: 300px;
}
</style>